package husc.se.ndung.soiphubaimobile;

import android.content.Context;
import android.content.SharedPreferences;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;

/**
 * Created by DungNguyen on 6/16/2015.
 */
public class Utils {
    public static String KeyUserName = "UserName";
    public static String KeyPassword = "Password";
    public static String KeyDomain = "IP";
    public static String KeyPort = "Port";

    public static void setKeyValue(Context context, String key, String value) {
        SharedPreferences sharedPref = context.getSharedPreferences("settingData", context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static String getValueByKey(Context context, String key, String defValue) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("settingData", context.MODE_PRIVATE);
        return sharedPreferences.getString(key, defValue);
    }

    private static String getURLService(Context context) {
        String ip = getValueByKey(context, "IP", "http://192.168.56.1");//http://spb.somee.com
        //String ip = "http://192.168.56.1";
        String port = getValueByKey(context, "Port", "8085");
        //String port = "8085";
        String url = "" + ip + ":" + port + "/ServiceChiTietMay.asmx?WSDL";
        return url;
    }

    public static Object sendRequest(Context context, String METHOD_NAME, ArrayList<String> params) throws Exception {
        String url = getURLService(context);
        final String NAMESPACE = "http://soiphubai.com/";
        final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {
                String param = params.get(i);
                String[] rs = param.split(":");
                if (rs.length == 2)
                    request.addProperty(rs[0], rs[1]);
            }
        }

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        MarshalFloat marshal = new MarshalFloat();
        marshal.register(envelope);
        HttpTransportSE androidHttpTransport =
                new HttpTransportSE(url);
        androidHttpTransport.call(SOAP_ACTION, envelope);
        return envelope.getResponse();
    }
}
